import dbm
import json
from flask import Flask, request, jsonify, send_from_directory
import argparse

app = Flask(__name__, static_url_path='/static', static_folder='static')

# 打开或创建 dbm 数据库文件
db = dbm.open('matrices.dbm', 'c')


@app.route('/')
def index():
    return send_from_directory('static', 'index.html')


@app.route('/matrix/<name>', methods=['GET', 'POST'])
def matrix(name):
    if request.method == 'POST':
        # 更新矩阵数据
        data = request.json
        db[name] = json.dumps(data)
        db['_'] = json.dumps(data)
        return jsonify({'message': f'Matrix {name} updated successfully.'})
    else:
        # 获取矩阵数据
        data_str = '[[0]]'
        if name in db:
            data_str = db[name].decode('utf-8')
        data = json.loads(data_str)
        db['_'] = data_str
        return jsonify(data)


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-p', '--port', type=int, default=5000, help='port to run the application on')
    args = parser.parse_args()

    app.run(port=args.port)
